package cn.edu.dutir.lucene;

import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class LuceneIndexDeleter {
	private LuceneIndexDeleter() {
	};

	public static void main(String[] args) {
		String usage = "java cn.edu.dutir.unit.lucene.LuceneIndexDeleter <index_dir> <unique_term>";
		if (args.length < 2) {
			System.err.println("Usage: " + usage);
			System.exit(1);
		}
		try {
			Directory directory = FSDirectory.getDirectory(args[0], false);
			IndexReader reader = IndexReader.open(directory);
			
			deleteByTerm(reader, args[1]);
						
			reader.close();
			directory.close();

		} catch (Exception e) {
			System.out.println(" caught a " + e.getClass()
					+ "\n with message: " + e.getMessage());
		}
	}
	
	public static void deleteById(IndexReader reader, int docNum){
		try {
			reader.deleteDocument(docNum);
		} catch (Exception e) {
			System.out.println(" caught a " + e.getClass()
					+ "\n with message: " + e.getMessage());
		}
	}
	
	public static int deleteByTerm(IndexReader reader, String term){
		Term termQuery = new Term("contents", term);
		int deleted = 0;
		try {
			deleted = reader.deleteDocuments(termQuery);
			System.out.println(deleted + " document deleted");
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("deleted " + deleted + " documents containing "
				+ term);
		return deleted;
	}
}
